package flex.cc.order.manage.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.core.support.BaseController;
import flex.cc.core.utils.RequestUtil;
import flex.cc.order.manage.dto.order.OrderPushImgEntity;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.order.manage.service.OrderPushImgService;
import flex.cc.util.FileDownloadUtil;
import flex.cc.wrapper.WrapMapper;
import flex.cc.wrapper.Wrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
*
* @author WANGCONG
* 2022年3月2日上午10:25:46
* @desc 救援单图片回传记录管理
*/
@RestController
@RequestMapping(value = "/order/pushImg")
public class PushImgManageController extends BaseController {

	@Resource
    private OrderMainService orderMainService;
	@Resource
	private OrderPushImgService orderPushImgService;
	
	/**
	*
	* @author WANGCONG
	* 2022年3月2日下午14:06:12
	* @desc 分页查询
	*/
	@PostMapping(value = "/queryListWithPage")
    @ApiOperation(httpMethod = "POST", value = "查询预约服务订单列表")
    public Wrapper<IPage<OrderPushImgEntity>> queryOrderListWithPage(@ApiParam(name = "order", value = "预约服务订单信息") @RequestBody Map<String, Object> reqVo) {
        logger.info("查询预约服务订单列表={}", reqVo);
        OrderPushImgEntity vo = new OrderPushImgEntity();
        vo.setStartTime( PublicUtil.isNotEmpty(reqVo.get("startTime")) ? reqVo.get("startTime").toString() : null ); //起止时间
        vo.setEndTime( PublicUtil.isNotEmpty(reqVo.get("endTime")) ? reqVo.get("endTime").toString() : null );
        vo.setPageNum( Integer.parseInt(String.valueOf(reqVo.get("pageNum"))) );  //分页
        vo.setPageSize( Integer.parseInt(String.valueOf(reqVo.get("pageSize"))) );
        IPage<OrderPushImgEntity> page = orderPushImgService.queryListWithPage(vo);
        return WrapMapper.ok(page);
    }
	
	/**
	*
	* @author WANGCONG
	* 2022年3月2日下午17:25:06
	* @desc 图片回传模板下载
	*/
	@PostMapping(value = "/exportTemplate")
    @ApiOperation(httpMethod = "POST", value = "图片回传模板下载")
	public void exportTemplate(HttpServletRequest request, HttpServletResponse response){
		logger.info("图片回传模板下载");
		String fileParentPath = System.getProperty("user.dir") + File.separator + "order" + File.separator + System.currentTimeMillis();
		String fileName = "图片回传模板";
		orderPushImgService.downLoadTemplate(request, response, fileParentPath, fileName);
		String filepath = fileParentPath + File.separator + fileName + ".xlsx";
        FileDownloadUtil.downloadByFilepath(request, response, filepath);
	}
	
	/**
	*
	* @author WANGCONG
	* 2022年3月3日上午09:25:18
	* @desc 图片回传模板导入
	*/
	@SuppressWarnings("resource")
	@PostMapping(value = "/upFile")
    @ResponseBody
    public Wrapper<String> upFile(@RequestParam("excelFile") MultipartFile excelFile) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("status", "success");
        result.put("msg", "成功");
        InputStream in = excelFile.getInputStream();
        try {
        	OPCPackage opcPackage = OPCPackage.open(in);
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(opcPackage);
			XSSFSheet sheet = xssfWorkbook.getSheetAt(0);//工作表对象
            int rowLength = sheet.getLastRowNum();//data数据总行数（抛去标题头）
            Row row = sheet.getRow(0);//工作表的列
            int colLength = row.getLastCellNum();//总列数
            if(colLength!=1){
            	result.put("status", "error");
        		result.put("msg", "导入文件列数与模板要求不符");
        		return WrapMapper.ok(JSON.toJSONString(result));
            }
            if(rowLength==0){
            	result.put("status", "error");
        		result.put("msg", "导入文件信息为空");
        		return WrapMapper.ok(JSON.toJSONString(result));
            }
            if(rowLength>200){
            	result.put("status", "error");
        		result.put("msg", "导入文件行数不得超过200条");
        		return WrapMapper.ok(JSON.toJSONString(result));
            }
            List<String> ownerOrderNoList = new ArrayList<String>();
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            	XSSFRow xssfRow = sheet.getRow(rowNum);
            	if (xssfRow != null) {
            		XSSFCell r1 = xssfRow.getCell(0);
                    String ownerOrderNo = getValue(r1);   //来源单号
                    if(PublicUtil.isEmpty(ownerOrderNo)){
                    	result.put("status", "error");
                		result.put("msg", "有空值，请补充完整");
                		return WrapMapper.ok(JSON.toJSONString(result));
                    }
                    ownerOrderNoList.add(ownerOrderNo);		
            	}
            }
            Date importTime = new Date();
            //TODO 预先插入t_order_push_img一条数据，异步线程执行任务
            OrderPushImgEntity vo = new OrderPushImgEntity();
            LoginAuthDto loginUser = RequestUtil.getLoginUser();
            String dataId = UUID.randomUUID().toString().replace("-", "");
            vo.setDataId(dataId);
            vo.setCreateTime(new Date());
            vo.setImportNumber(ownerOrderNoList.size());
            vo.setImportTime(importTime);
            vo.setFileName(excelFile.getOriginalFilename());
            vo.setCreater(loginUser.getUserCode());
            vo.setStatus("0");//状态，0-导入中，1-完成
            orderPushImgService.insert(vo);
            orderPushImgService.asyncPushImg(dataId, loginUser, ownerOrderNoList);
		} catch (Exception e) {
			result.put("status", "error");
			result.put("msg", "系统异常，请联系运营人员");
		}
        return WrapMapper.ok(JSON.toJSONString(result));
        
	}
	
	/**
	*
	* @author WANGCONG
	* 2022年3月3日下午15:35:09
	* @desc 图片回传报告下载前验证
	*/
	@PostMapping(value = "/checkReport/{dataId}")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "报告下载验证")
    public Wrapper<String> checkReport(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String dataId) {
        logger.info("报告下载 -- downloadReport() ====> ", dataId);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("status", "success");
        result.put("msg", "成功");
        OrderPushImgEntity pushImgVo = orderPushImgService.queryByDataId(dataId);
        if(pushImgVo==null){
        	result.put("status", "error");
    		result.put("msg", "当前数据已不存在，请刷新后重试");
    		return WrapMapper.ok(JSON.toJSONString(result));
        }
        String status = pushImgVo.getStatus();
        String reportUrl = pushImgVo.getReportUrl();
        if(!status.equals("1") || PublicUtil.isEmpty(reportUrl)){
        	result.put("status", "error");
    		result.put("msg", "当前数据还未执行完成，请刷新后重试");
    		return WrapMapper.ok(JSON.toJSONString(result));
        }
        return WrapMapper.ok(JSON.toJSONString(result));
    }
	
	/**
	*
	* @author WANGCONG
	* 2022年3月3日下午15:42:16
	* @desc 图片回传报告下载
	*/
	@PostMapping(value = "/downloadReport/{dataId}")
    @ApiOperation(httpMethod = "POST", value = "图片回传模板下载")
	public void downloadReport(HttpServletRequest request, HttpServletResponse response, @PathVariable String dataId){
		OrderPushImgEntity pushImgVo = orderPushImgService.queryByDataId(dataId);
		String reportUrl = pushImgVo.getReportUrl();
		FileDownloadUtil.downloadReport(request, response, reportUrl);
	}
	
	@SuppressWarnings({ "deprecation", "static-access" })
	public static String getValue(XSSFCell xssfRow) {
    	if(xssfRow==null){
    		return "";
    	}
		String value="";
        if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
        	value = String.valueOf(xssfRow.getBooleanCellValue()).trim();
        } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
            value = String.valueOf(xssfRow.getNumericCellValue()).trim();
        } else {
        	value = String.valueOf(xssfRow.getStringCellValue()).trim();
        }
        return value;
    }
	
}
